# -*- coding: utf-8 -*-
import math

from collections import namedtuple
from odoo import api, fields, models, SUPERUSER_ID, tools
from odoo.addons.resource.models.resource import float_to_time, HOURS_PER_DAY

from datetime import datetime, date, timedelta, time
from pytz import timezone, UTC

from odoo.exceptions import UserError

DummyAttendance = namedtuple('DummyAttendance', 'hour_from, hour_to, dayofweek, day_period, week_type')

class HrLeave(models.Model):
    _name = 'hr.leave'
    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin', 'base.approve','hr.leave']
    sheet_id=fields.Many2one('hr.leave.sheet')
    department_id=fields.Many2one('hr.department',related='sheet_id.department_id',store=True)

    # request_date_from=fields.Datetime(string=u'开始时间')
    # request_date_to = fields.Datetime(string=u'结束时间')
    _sql_constraints = [
        ('name_uniq', 'unique (name)', "单号我必须唯一!"),
    ]

    def cancel_line_ids(self):
        for line in self.line_ids:
            line.unlink()
    def create_line_ids(self):
        date1 = self.request_date_from
        date2 = self.request_date_to
        if date1 != date2:
            while date1 <= date2:
                resource_calendar_id = self.employee_id.get_current_calendar_id(date1)
                hours = self.compute_leave_hours(resource_calendar_id, date1)
                self.env['hr.leave.line'].create({
                    'leave_id': self.id,
                    'hours': hours,
                    'date': date1
                })
                date1 = date1 + timedelta(days=1)

        else:
            resource_calendar_id = self.employee_id.get_current_calendar_id(date1)
            total_hours = self.compute_leave_hours(resource_calendar_id, date1, time_start=self.request_hour_from,
                                                   time_end=self.request_hour_to)
            self.env['hr.leave.line'].create({
                'leave_id':self.id,
                'hours':total_hours,
                'date':self.request_hour_from
            })







    state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('to approve', u'待审核'),
        ('confirm', u'拒绝'),
        ('rejected', u'拒绝'),
        ('done', u'完成'),
    ], string=u"状态", related='sheet_id.state', track_visibility='onchange',store=True)
    remark=fields.Char(string=u'理由')

    @api.onchange( 'request_date_to',
                  'request_date_from',
                  'employee_id')
    def _onchange_request_date_from_to(self):
        if self.request_date_from:
            print(self.request_date_from)
            calendar_id=self.employee_id.get_current_calendar_id(self.request_date_from)
            if not calendar_id:
                raise UserError('找不到' + self.employee_id.name + '对应的班别')
            dayofweek = self.request_date_from.weekday()
            attendances = calendar_id.attendance_ids.filtered(
                            lambda x: x.dayofweek == str(dayofweek))
            if not attendances:
                raise UserError('未找到应出勤，无需请假')
            if not self.request_date_to:
                self.request_date_to=self.request_date_from
            hour_from = attendances[0].hour_from
            hour, min = str(hour_from).split('.')
            if not float(min):
                hour_from=hour
            else:
                hour_from=str(hour_from)

            self.request_hour_from = str(hour_from)
        if self.request_date_to:
            calendar_id = self.employee_id.get_current_calendar_id(self.request_date_from)
            if not calendar_id:
                raise UserError('找不到'+self.employee_id.name+'对应的班别')
            dayofweek = self.request_date_from.weekday()
            attendances = calendar_id.attendance_ids.filtered(
                lambda x: x.dayofweek == str(dayofweek))
            if not attendances:
                raise UserError('未找到应出勤，无需请假')
            hour_to=attendances[1].hour_to
            hour,min=str(hour_to).split('.')
            if not float(min):
                hour_to = hour
            else:
                hour_to = str(hour_to)

            self.request_hour_to = str(hour_to)




    def name_get(self):
        result = []
        name = self._rec_name
        if name in self._fields:
            convert = self._fields[name].convert_to_display_name
            for record in self:
                result.append((record.id, convert(record[name], record)))
        else:
            for record in self:
                result.append((record.id, "%s,%s" % (record._name, record.id)))

        return result

    def compute_leave_hours(self,calendar_id,date,time_start=False,time_end=False):
        if not time_end:
            return calendar_id.hours_per_day
        time_start=float(time_start)
        time_end=float(time_end)
        print (time_end)
        attendances = calendar_id.attendance_ids.filtered(
            lambda x: x.dayofweek == str(date.weekday()))
        if not attendances:
            raise UserError(str(date)+'沒有排班不需要请假')

        attendance_start=attendances[0]
        attendance_end=attendances[1]
        # 如果请假开始时间小于上班开始时间取上班开始时间
        if time_start<=attendance_start.hour_from:
            start=attendance_start.hour_from
        elif time_start>=attendance_start.hour_to and time_start<=attendance_end.hour_from:
            start=attendance_end.hour_from
        elif time_start>attendance_end.hour_to:
            raise UserError('请假开始时间不能大于下班时间')
        else:
            start=time_start

        # 如果请假结束时间大于下班时间取下班时间
        if time_end>=attendance_end.hour_to:
            end= attendance_end.hour_to
        elif time_end>=attendance_end.hour_to and time_start<=attendance_end.hour_from:
            end=attendance_end.hour_to
        elif time_end<attendance_start.hour_from:
            raise UserError('请假结束时间不能小于上班时间')
        else:
            end=time_end
        deduct_time=0
        if start<=attendance_start.hour_to and end >=attendance_end.hour_from:
            deduct_time=calendar_id.lunch_time
        hours=end-start -deduct_time
        print (hours)
        return hours















    def check_rules(self):
        date1 = self.request_date_from
        date2 = self.request_date_to
        calendars = []
        while date1 <= date2:
            resource_calendar_id = self.employee_id.get_current_calendar_id(date1)
            calendars.append(resource_calendar_id)
            date1 = date1 + timedelta(days=1)
        if len(calendars) > 1:
            raise UserError(self.employee_id.name + '请假时间跨班别，请检查')

    @api.onchange('request_date_from_period', 'request_hour_from', 'request_hour_to',
                  'request_date_from', 'request_date_to',
                  'employee_id')
    def _onchange_request_parameters(self):
        if not self.request_date_from:
            self.date_from = False
            return

        if self.request_unit_half or self.request_unit_hours:
            self.request_date_to = self.request_date_from

        if not self.request_date_to:
            self.date_to = False
            return

        date1 = self.request_date_from
        date2 = self.request_date_to
        total_hours=0
        calendar_id = self.employee_id.get_current_calendar_id(date1)
        work_hours=calendar_id.hours_per_day
        if date1!=date2:
            while date1 <= date2:
                print (date1,date1.weekday())
                resource_calendar_id = self.employee_id.get_current_calendar_id(date1)
                hours=self.compute_leave_hours(resource_calendar_id,date1)
                total_hours+=hours
                date1 = date1 + timedelta(days=1)

        else:
            resource_calendar_id = self.employee_id.get_current_calendar_id(date1)
            total_hours=self.compute_leave_hours(resource_calendar_id,date1,time_start=self.request_hour_from,time_end=self.request_hour_to)

        self.number_of_days=total_hours/work_hours




class HrLeaveLine(models.Model):
    _name = 'hr.leave.line'
    _description = '加班明細'
    date=fields.Date(string='日期')
    leave_id=fields.Many2one('hr.leave',index=True,ondelete='cascade')
    employee_id=fields.Many2one('hr.employee',related='leave_id.employee_id',store=True,index=True)
    hours=fields.Float(string=u'小时')
    leave_type=fields.Selection([
        ('1','平时请假'),
        ('2', '周末请假')
    ],compute='compute_leave_type',store=True)
    @api.depends('date','employee_id')
    def compute_leave_type(self):
        for record in self:
            if record.date.weekday() in (0,1,2,3,4):
                record.leave_type='1'
            else:
                record.leave_type = '2'






    hours=fields.Float(string=u'小时')